<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-button type="primary" @click="showAddCate">添加分类</el-button>
            </el-row>
            <tree-table class="tree-table" :show-index="true" index-text="#" :data="catelist" :columns="columns"
                :selection-type="false" :expand-type="false" border>
                <!-- 是否有效 -->
                <template slot="isok" slot-scope="scope">
                    <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color: lightgreen;"></i>
                    <i class="el-icon-error" v-else style="color: red;"></i>
                </template>
                <!-- 等级排序 -->
                <template slot="level" slot-scope="scope">
                    <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
                    <el-tag size="mini" type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
                    <el-tag size="mini" type="warning" v-else-if="scope.row.cat_level===2">三级</el-tag>
                </template>
                <!-- 操作 -->
                <template slot="opt" slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" @click="showEditCateDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row.cat_id)">删除</el-button>
                </template>
            </tree-table>
            <!-- 分页功能 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加分类的对话框 -->
        <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
            <el-form :model="addCateForm" :rules="addCateRules" ref="addCateRef" label-width="100px">
                <el-form-item label="分类名称:" prop="cat_name">
                    <el-input v-model="addCateForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类:">
                    <!-- options用来指定数据源 -->
                    <!-- props用来指定配置对象 -->
                    <el-cascader v-model="selectedKeys" :options="parentDataCate" :props="cascaderProps"
                        @change="parentCateChanged" clearable collapse-tags></el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addCateDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAddCate">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑分类对话框 -->
        <el-dialog title="编辑分类" :visible.sync="editCateDialogVisible" width="50%">
            <el-form :model="editCateForm" :rules="editCateRules" ref="editCateRef" label-width="100px">
                <el-form-item label="分类名称:" prop="cat_name">
                    <el-input v-model="editCateForm.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editCateDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEditCate">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                catelist: [],
                queryInfo: {
                    type: 3,
                    pagenum: 1,
                    pagesize: 5
                },
                total: 0,
                //为table指定列的定义
                columns: [
                    {
                        label: '分类名称',
                        prop: 'cat_name'
                    },
                    {
                        label: '是否有效',
                        prop: 'cat_deleted',
                        //表示，当前列定义为模板列
                        type: 'template',
                        //表示当前这一列使用模板名称
                        template: 'isok'
                    },
                    {
                        label: '排序',
                        //表示，当前列定义为模板列
                        type: 'template',
                        //表示当前这一列使用模板名称
                        template: 'level'
                    },
                    {
                        label: '操作',
                        //表示，当前列定义为模板列
                        type: 'template',
                        //表示当前这一列使用模板名称
                        template: 'opt'
                    }

                ],
                addCateDialogVisible: false,
                addCateForm: {
                    // 要添加分类的名称
                    cat_name: '',
                    // 父级分类的id
                    cat_pid: 0,
                    // 分类的等级，默认要添加的是一级分类
                    cat_level: 0
                },
                addCateRules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' }
                    ]
                },
                //父级数据列表
                parentDataCate: [],
                // 指定级联选择器的配置对象
                cascaderProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                    expandTrigger: 'hover',
                    checkStrictly: true
                },
                // 选中的父级分类的ID数组
                selectedKeys: [],
                editCateDialogVisible: false,
                editCateForm: {
                    cat_id: '',
                    cat_name: ''
                },
                editCateRules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
                if (res.meta.status !== 200) return this.$message.error('获取分类数据列表失败')
                this.catelist = res.data.result
                this.total = res.data.total
            },
            handleSizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                this.getCateList()
            },
            handleCurrentChange(newPage) {
                this.queryInfo.pagenum = newPage
                this.getCateList()
            },
            showAddCate() {
                this.getParentList()
                this.addCateDialogVisible = true
            },
            // 获取父级分类的数据列表
            async getParentList() {
                const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
                if (res.meta.status !== 200) { return this.$message.error('获取父级分类数据失败') }
                //获取父级列表数据成功
                this.parentDataCate = res.data
            },
            // 选择项发生变化触发此函数
            parentCateChanged() {
                console.log(this.selectedKeys);
                if (this.selectedKeys.length > 0) {
                    this.addCateForm.cat_level = this.selectedKeys.length;
                    this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
                    return;
                } else {
                    this.addCateForm.cat_level = 0;
                    this.addCateForm.cat_pid = 0;
                }
            },
            saveAddCate() {
                this.$refs.addCateRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post('categories', this.addCateForm)
                    if (res.meta.status !== 201) {
                        this.$message.error('创建分类失败')
                    }
                    this.$message.success('添加分类成功')
                    this.getCateList()
                    this.addCateDialogVisible = false
                })
            },
            addCateDialogClosed() {
                this.$refs.addCateRef.resetFields()
                this.selectedKeys = []
                this.addCateForm.cat_level = 0
                this.addCateForm.cat_pid = 0
            },
            showEditCateDialog(cate) {
                this.editCateForm.cat_id = cate.cat_id
                this.editCateForm.cat_name = cate.cat_name
                this.editCateDialogVisible = true
            },
            saveEditCate() {
                this.$refs.editCateRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put('categories/' + this.editCateForm.cat_id, { cat_name: this.editCateForm.cat_name })
                    console.log(res);
                    if (res.meta.status !== 200) return this.$message.error('修改分类失败')
                    this.$message.success('修改分类成功')
                    this.getCateList()
                    this.editCateDialogVisible = false
                })
            },
            async deleteCate(id) {
                const ret = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                if (ret !== 'confirm') {
                   return this.$message.info('已经取消删除该分类')
                }
                const { data: res } = await this.$http.delete('categories/' + id)
                if (res.meta.status !== 200) return this.$message.error('删除分类失败')
                this.$message.success('删除分类成功')
                this.getCateList()
            }
        }
    }
</script>
<style lang="less" scoped>
    .tree-table {
        margin-top: 15px;
    }

    .el-cascader {
        width: 100%;
    }
</style>